package com.woniuxy.three.pms.shiro;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.three.pms.bean.UserBean;
import com.woniuxy.three.pms.user.service.IUserService;
import com.woniuxy.three.pms.util.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.Duration;
import java.time.temporal.ChronoUnit;

/**
 * @ProjectName: Pms
 * @Package: com.woniuxy.three.pms.shiro
 * @ClassName: UserCacheRealm
 * @Author: 12092
 * @Description:  会员缓存登录使用的Realm
 * @Date: 2019/6/28 14:39
 * @Version: 1.0
 */
@Slf4j
public class UserCacheRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;

    @Autowired
    private CacheUtil cacheUtil;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String mobile = upToken.getUsername();
        String redisResult = null;
        UserBean user = null;
        if (!StringUtils.isBlank(mobile)){
            redisResult = cacheUtil.getValueWithKey(mobile);
            if (!StringUtils.isBlank(redisResult)){
                user = userService.findUserByMobile(mobile);
                user.setPassword(redisResult);
                if (user!=null){
                    try {
                        String result = new ObjectMapper().writeValueAsString(user);
                        cacheUtil.cacheWithKeyValue("login_info_"+mobile,result);
                    } catch (JsonProcessingException e) {
                        log.error("转换JSON对象字符串失败");
                        e.printStackTrace();
                    }
                }
            }
        }
        AuthenticationInfo info = new SimpleAuthenticationInfo(mobile,redisResult,getName());
        return info;
    }
}
